package com.ccys.db.handler;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccys.common.util.Kit;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.cache.UserUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;


/**
 * 日期处理
 */
@Slf4j
@Component
@RestControllerAdvice
public class CustomDateResponseBodyAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 返回true表示支持对响应进行处理
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 对响应数据进行处理
        // 在这里可以对body中的日期类型数据进行适当的修改
        /**
         * ResponseResult(code=200, msg=请求成功, data=PageInfo{pageNum=1, pageSize=10, size=3, startRow=1, endRow=3, total=3, pages=1, list=Page{count=true, pageNum=1, pageSize=10, startRow=0, endRow=10, total=3, pages=1, countSignal=null, orderBy='null', orderByOnly=false, reasonable=false, pageSizeZero=false}, prePage=0, nextPage=0, isFirstPage=true, isLastPage=true, hasPreviousPage=false, hasNextPage=false, navigatePages=8, navigateFirstPage1, navigateLastPage1, navigatepageNums=[1]}, otherData=null)
         */
        if (body != null && body instanceof ResponseResult) {
            ResponseResult response = (ResponseResult) body;
            Object data = response.getData();
            if(data != null) {
                try {
                    if (data instanceof PageInfo) {
                        PageInfo pageInfo = (PageInfo) data;
                        List list = pageInfo.getList();
                        for (int i =0; i<list.size();i++) {
                            JSONObject o = (JSONObject)JSONObject.toJSON(list.get(i));
                            for (String s : o.keySet()) {
                                if(o.get(s) instanceof Date) {
                                    if(o.get(s) != null) {
                                        //log.info("===格式化前的日期：" + o.get(s).toString());
                                        // 创建日期时间格式化器
                                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                        //ZonedDateTime zonedDateTime = ZonedDateTime.of(o.get(s).toString(), "UTC");
                                        Date date  = (Date) o.get(s);
                                        // 将Date对象转换为Instant对象
                                        Instant instant = date.toInstant();

                                        // 获取系统默认时区
                                        ZoneId zoneId = ZoneId.systemDefault();

                                        // 将Instant对象转换为ZonedDateTime对象
                                        ZonedDateTime zonedDateTime = instant.atZone(zoneId);

                                        // country_id 医生与患者都有国家
                                        //int hours = UserUtil.getCurLoginUserTimeZone();
                                        // 指定目标时区为UTC+8
                                        ZoneOffset targetZoneOffset = ZoneOffset.ofHours(10);

                                        // 将日期时间格式化为目标时区的字符串
                                        String formattedDateTime = zonedDateTime.withZoneSameInstant(targetZoneOffset).format(formatter);
                                        // 逻辑未处理完
                                        //System.out.println("加时区后的时间：" + formattedDateTime);

                                        o.put(s,formattedDateTime);
                                        //o.put(s,Kit.parseDateTimeStr("2012-12-12 12:12:12", "yyyy-MM-dd HH:mm:ss"));
                                        //System.out.println("修改后的数据：" + o.get(s));
                                        //o.put("test", "添加测试数据");
                                    }

                                }
                            }

                        }

                    }else{
                        if (data instanceof List) {

                        }else {

                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    log.error("日期转换处理失败");
                }

            }


            //response.setDateValue(new Date()); // 修改日期类型数据为当前时间
        }
        return body;
    }
}
